package cac.gkinterface.service;

import cac.common.CallInterFace.service.CallInterfaceService;
import cac.common.CreatMsgId;
import cac.fenjian.resource.wmsdeliverplan.service.WmsDeliverPlanService;
import cac.gkinterface.dao.WorkPackageDao;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.cac.dme.adapter.rest.msg.ResponseMsg;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class WorkService {

    @Autowired
    private WorkPackageDao workPackageDao;
    @Autowired
    private CallInterfaceService callInterfaceService;
    @Autowired
    private WorkService workService;
    @Autowired
    private WmsDeliverPlanService wmsDeliverPlanService;

    //读取xml文件中ao任务并插入到数据库
    public int insertMesAoTask(HashMap hashMap) {
        workPackageDao.insertOutBillH(hashMap);
        //yebo 新增，更新工作包站位
        workPackageDao.updatePackageMadeCenter(hashMap);
        return workPackageDao.insertMesAoTask(hashMap);
    }

    //读取xml文件中工作包任务并插入到数据库
    public int insertWorkPackage(HashMap hashMap) {

        return workPackageDao.insertWorkPackage(hashMap);
    }

    public int updateWorkPackage(HashMap hashMap) {
        workPackageDao.updateAoWeek(hashMap);
        return workPackageDao.updateWorkPackage(hashMap);
    }

    //读取xml文件中物料信息并插入到数据库
    public int insertMesMaterial(HashMap hashMap) {
        workPackageDao.insertOutBillL(hashMap);
        return workPackageDao.insertMesMaterial(hashMap);
    }

    //更新下达日计划中的时间
    public int updateDailyTime(HashMap hashMap) {
        workPackageDao.updateDailyPackTime(hashMap);
        return workPackageDao.updateDailyAoTime(hashMap);
    }

    //修改bill
    public int updateMatchBill(String groupNo) {
        return workPackageDao.updateMatchBill(groupNo);
    }

    //修改aoTask
    public int updateAoTask(String groupNo) {
        return workPackageDao.updateAoTask(groupNo);
    }

    //下发测试日志
    public Integer issuedTest(HashMap hashMap) {
        return workPackageDao.issuedTest(hashMap);
    }

    /**
     * 记录erp日志
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void insertErpLog(HashMap log) {
        try {
            workPackageDao.insertErpExchangeLog(log);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateErpBdata(HashMap log) {
        try {
            workPackageDao.updateErpBdata(log);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateErpLog(HashMap log) {
        try {
            workPackageDao.updateErpExchangeLog(log);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean queryIsRepeat(HashMap log) {
        try {
            int flag = workPackageDao.queryIsRepeat(log);
            if (flag == 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    //ERP返回处理结果到wms
    public void resultBackToWms(JSONArray paramJsonObjectArray, String msgId, String func) {
        //多个消息id
        //List<HashMap> list = paramJsonObjectArray.toJavaList(HashMap.class);
        List<HashMap> list = JSONArray.parseArray(paramJsonObjectArray.toJSONString(), HashMap.class);
        for (HashMap map : list) {
            map.put("func", func);
            map.put("BData", map.toString());
            map.put("parentMsgId", msgId);
            map.put("system", "ERP");
            log.info("ERP查询101处理结果接口参数:" + map);
            //插入信息日志：ERP-101(记录消息id)
            this.issuedBack(map);
        }

    }

    //ERP主动查询wms处理结果,WMS返回处理结果
    public void resultBackToErp(JSONArray paramJsonObjectArray, String msgId) {
        HashMap backToErp = new HashMap();
        List datas = new ArrayList();
        HashMap issuedTest = new HashMap();
        String rstl = "";
        try {
            //多个消息id
            // List<HashMap> list = paramJsonObjectArray.toJavaList(HashMap.class);
            List<HashMap> list = JSONArray.parseArray(paramJsonObjectArray.toJSONString(), HashMap.class);
            for (HashMap map : list) {
                List<HashMap> rsl = workPackageDao.searchWmsResult(map);
                for (HashMap data : rsl) {
                    if (Objects.isNull(data.get("failMsg"))) {
                        data.put("failMsg", "");
                    }
                    data.put("system", "MSMS");
                    datas.add(data);
                }
                if (rsl.size() == 0) {
                    HashMap emptyData = new HashMap();
                    emptyData.put("retCode", "0");
                    emptyData.put("system", "MSMS");
                    emptyData.put("msgId", map.get("msgId"));
                    emptyData.put("failMsg", "未找到数据");
                    datas.add(emptyData);
                }
            }
            backToErp.put("data", datas);
            backToErp.put("msgId", msgId);
            backToErp.put("func", "101-ERP-RCVMSG");
            log.info("erp主动查询结果返回！");
            callInterfaceService.sendBData("sendBData", "两网传输-发送业务数据",
                    CallInterfaceService.encodeBData(JSON.toJSONString(backToErp)), "反馈ERP查询结果");
            //接口日志参数
            if (datas.toString().length() > 3900) {
                issuedTest.put("BData", datas.toString().substring(0, 3900));
            } else {
                issuedTest.put("BData", datas.toString());
            }
            issuedTest.put("type", "101-ERP-RCVMSG");
            issuedTest.put("msgId", msgId);
            issuedTest.put("retCode", "1");
            rstl = "操作成功";
        } catch (Exception e) {
            e.printStackTrace();
            rstl = ExceptionUtils.getFullStackTrace(e);
            if (rstl.length() > 200) {
                rstl = rstl.substring(0, 200);
            }
            issuedTest.put("result", rstl);
            issuedTest.put("retCode", "0");
        } finally {
            issuedTest.put("failMsg", rstl);
            workService.issuedTest(issuedTest);
        }
    }

    /**
     * 工艺更改更改AO
     **/
    public void updateAoByProcessChange(HashMap map) {
        int cnt = workPackageDao.queryAoTaskIsExists(map);
        //更新AO下物料清单的组号
        workPackageDao.updateAoMatchBillGroupCodeBatch(map);
        if (cnt > 0) {
            return;
        }
        workPackageDao.insertOutBillH(map);
        workPackageDao.insertTaskAoForProcessChange(map);
    }

    public void insertAoChangeTmp(HashMap map) {
        workPackageDao.insertAoChangeTmp(map);
    }

    /**
     * 工艺更改bill数据备份以及删除作废的物料
     **/
    public void matchBillBak(HashMap map) {
        //作废的物料数据备份
        workPackageDao.addMatchBillDel(map);
        //删除物料数据
        workPackageDao.deleteMatchBillDel(map);
    }

    /**
     * 工艺更改物料变更
     */
    public void updateMaterialByProcessChange(HashMap map) {
        //判断此物料是否存在
        int cnt = workPackageDao.queryMaterialIsExists(map);
        if (cnt > 0) {//物料存在
            cnt = workPackageDao.queryMaterialIsChange(map);
            if (cnt == 0) {//物料发生了变更
                //更新ms_ao_match_bill表信息
                workPackageDao.updateMatchBillByProcessChange(map);
                //更新ms_ao_match_info表信息  2023-11-10 yebo 新增
                workPackageDao.updateAreadSortMaterialMatchInfo(map);
            } else {//没发生变化只更新组号
                workPackageDao.updateMatchBillGroupCodeByProcessChange(map);
            }
        } else {//物料不存在
            workPackageDao.insertMatchBillByProcessChange(map);
        }
    }


    //erp返回消息结果记录
    public Integer issuedBack(HashMap hashMap) {
        return workPackageDao.issuedBack(hashMap);
    }


    //修改日志
    public Integer updateLog(HashMap hashMap) {
        return workPackageDao.updateLog(hashMap);
    }

    //mes扫码移交确认
    public void DeliveryConfirm(HashMap map) {
        String status = map.get("STATUS").toString();
        if ("1".equals(status)) {
            HashMap param = workPackageDao.searchWmsDeliveryPlanStatus(map);
            int wmsStatus = Integer.parseInt(param.get("DELIVERY_STATUS").toString());
            if (wmsStatus == 1) {
                //未收到移交，在此处移交并下账
                wmsDeliverPlanService.MakeMaterialCheck(param);
            } else if (wmsStatus == 2) {
                //已移交，不处理
                return;
            }
        }else{
            return;
        }
    }
    public String selectShopByWdpId (HashMap map){
        return workPackageDao.selectShopByWdpId(map);
    }
}
